package org.infosys.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
/**
* @Description: 登录拦截器
* @Author: hank
* @Version: 1.0
* @Date:  2022/7/7 18:38
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 不为空，需要确认token是否正确
        if (!StringUtils.isEmpty(token)) {
            Object tokenValue = redisTemplate.opsForValue().get(token);
            if (!ObjectUtils.isEmpty(tokenValue)) {
                // 放行
                redisTemplate.opsForValue().set(token, tokenValue,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 拦截
        // 响应字符集
        response.setCharacterEncoding("UTF-8");
        // 响应数据格式
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;

    }
}
